package com.hqu.jim.dao.impl;

import com.hqu.jim.dao.AttendanceDao;
import com.hqu.jim.entity.Attendance;
import com.hqu.jim.tool.FileTool;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class AttendanceDaoImpl  implements AttendanceDao {

    private FileTool fileTool = new FileTool();

    @Override
    public List<Attendance> getAllUser(String fileName) {
        //读取文件并将内容更到最新
        List<Attendance> attendances = updateToNewTime(fileName);
        //将最新内容存到文件中
        fileTool.writeFile(fileName,attendances);
        return attendances;
    }

    @Override
    public boolean updateUserByUserSequence(String fileName,String sequence,String score){
        //获取数据集合
        List<Attendance> attendances = getAllUser(fileName);
        //通过学号查找并更新对象
        for (Attendance a:attendances) {
            if(a.getSequence().equals(sequence)){
               String[] marks = a.getMarks();
               marks[marks.length-1] = score;
               a.setMarks(marks);
            }
        }
        //存到文件中
        if(fileTool.writeFile(fileName,attendances))
            return true;
        else
            return false;
    }

    @Override
    public List<Attendance> updateToNewTime(String fileName){
        //获取数据集合
        List<Attendance> attendances = fileTool.readFile(fileName);
        //获取当前年月日
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String today = sdf.format(date);
        //获取文件里的最近年月日
        String[] marks = attendances.get(0).getMarks();
        String recentDate = marks[marks.length-1];
        if(recentDate.equals(today)==false){
            //添加当天的记分项
            String[] marks1 = Arrays.copyOf(marks,marks.length+1);
            System.arraycopy(marks,0,marks1,0,marks.length);
            marks1[marks1.length-1] = today;
            attendances.get(0).setMarks(marks1);
            for (int i = 1; i < attendances.size(); i++) {
                String[] marks2 = attendances.get(i).getMarks();
                String[] marks3 = Arrays.copyOf(marks2,marks2.length+1);
                System.arraycopy(marks2,0,marks3,0,marks2.length);
                marks3[marks3.length-1] = "0";
                attendances.get(i).setMarks(marks3);
            }
        }
        return attendances;
    }
}
